import { nextmeshEventCenter } from '@app-nextmesh/common/events/EventCenter';
import { getFormIndex, nmAppErrorLog } from '@app-nextmesh/common/utils';
import { CommandDialog2 } from '@app-nextmesh/components/Dialogs';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import {
  ENTITY_TYPE_VOLUME,
  ENTITY_TYPES,
  IMeshBoundaryLayer,
  IMeshDistribution,
  IMeshSize,
  ModelEventType,
  ModelPickSwitchEvent,
  ModelPickTypesEvent,
} from '@app-nextmesh/types';
import { NMMeshCtrlCmdDialogParams } from '@app-nextmesh/types/command';
import { events } from '@app-nextmesh/utils';
import { UiSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';

const isMeshSize = (
  value: IMeshBoundaryLayer | IMeshDistribution | IMeshSize,
): value is IMeshSize => value['MeshingDim'] != null;

export default function CmdControlDialog({
  title,
  onClose,
  initFormData,
  params,
  pickTypes,
  controlType,
  schema,
}: NMMeshCtrlCmdDialogParams<{
  id: string;
  formData: IMeshBoundaryLayer | IMeshDistribution | IMeshSize;
}>) {
  const { projectInfo, setProjectInfo } = useProjectStore((state) => state);
  const [formDataIndex, setFormDataIndex] = useState<number>(undefined);
  const [formData, setFormData] = useState<
    IMeshBoundaryLayer | IMeshDistribution | IMeshSize
  >(null);

  useEffect(() => {
    // 设置当前支持的拾取类型
    events.emit(ModelEventType.PickTypes, {
      types: pickTypes,
    } as ModelPickTypesEvent);
    let entityType = ENTITY_TYPE_VOLUME;
    if (params) {
      // 从id中解析出index
      setFormDataIndex(getFormIndex(params.id));

      setFormData(params.formData);

      if (isMeshSize(params.formData)) {
        entityType = ENTITY_TYPES[params.formData.MeshingDim];
      } else {
        entityType = params.formData.EntityType;
      }
    } else {
      // 新建时，进行初始化，自动命名
      let name: string = controlType;
      let count = 0;
      const meshControl = projectInfo?.meshControl?.params;
      if (meshControl) {
        count =
          meshControl[controlType]?.filter((value) => !value.isGlobal)
            ?.length ?? 0;
      }
      name = `${name}${count + 1}`;
      // 自动生成一个名称
      setFormData({
        Name: name,
        ...initFormData,
      });
      entityType = pickTypes[0];
    }
    if (entityType) {
      // 设置当前拾取类型
      events.emit(ModelEventType.SetCurrentPickType, {
        type: entityType,
        clear: true,
      } as ModelPickSwitchEvent);
    }
  }, [projectInfo, controlType, params]);
  const uiSchema: UiSchema = {
    SelectedEntities: {
      'ui:field': 'entity',
      pickTypes: pickTypes,
    },
  };
  const onSubmit = async (data) => {
    if (!data) {
      return;
    }
    let meshControl = projectInfo.meshControl;
    if (!meshControl) {
      meshControl = {
        params: {
          MeshSize: [],
          Distribution: [],
          BoundaryLayer: [],
        },
      };
    }
    if (!meshControl.params) {
      meshControl.params = {
        MeshSize: [],
        Distribution: [],
        BoundaryLayer: [],
      };
    }

    const dims = nextmeshEventCenter().pickType;
    if (dims?.length > 0) {
      if (controlType === 'MeshSize') {
        data.MeshingDim = dims[0];
      } else {
        data.EntityType = ENTITY_TYPES[dims[0]];
      }
    }
    if (formDataIndex !== undefined) {
      meshControl.params[controlType][formDataIndex] = data;
    } else {
      meshControl.params[controlType].push(data);
    }
    projectInfo.meshControl = meshControl;
    try {
      await documentV2.updateMeshControl(projectInfo.meshControl);
      setProjectInfo({ ...projectInfo });
      onClose();
    } catch (error) {
      nmAppErrorLog('CmdControl', 'onSubmit', error);
    }
  };
  return (
    <CommandDialog2
      title={title}
      formData={formData}
      schema={schema}
      extraUiSchema={uiSchema}
      onClose={onClose}
      onSubmit={onSubmit}
    />
  );
}
